﻿using MX.Core;
using MX.Core.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using UserCenter.Console.Sdk.Demo.Core;
using UserCenter.Console.Sdk.Demo.Models;
using UserCenter.Console.Sdk.Demo.Tools;

namespace UserCenter.Console.Sdk.Demo.Controllers
{
    public class HomeController : JsonNetController
    {

        public ActionResult Index()
        {
            return Content("Member Center SDK DEMO");
        }


        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        private string GetIP()
        {
            string result = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = Request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                result = "0.0.0.0";
            }
            return result;
        }

        private (bool Success, string Message, string Key) Send(TableInfo<SmsLog> tableInfo, string phone, string deviceId, string ip)
        {
            SmsLog smsLog = new SmsLog();
            Random random = new Random(smsLog.Key.GetHashCode());
            smsLog.CreateTime = DateTime.Now;
            smsLog.Code = random.Next(1000, 9999).ToString();
            smsLog.DeviceId = deviceId;
            smsLog.Ip = ip;
            smsLog.Phone = phone;
            var sendResult = SmsHelper.Send(phone, smsLog.Code);
            if (sendResult.Success)
                tableInfo.Table[smsLog.Key] = smsLog;
            return (sendResult.Success, sendResult.Message, smsLog.Key.ToString("D"));
        }

        private bool CheckSms(TableInfo<SmsLog> tableInfo, Func<SmsLog, bool> predicate, int time)
        {
            var lastLog = tableInfo.Table.Select(t => t.Value).
                 Where(predicate).
                 OrderByDescending(l => l.CreateTime).
                 Take(1).SingleOrDefault();
            if (lastLog != null)
            {
                if (lastLog.CreateTime.AddSeconds(time) > DateTime.Now)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return true;
            }
        }

        public JsonResult Sms(string phone, string deviceId)
        {

            string ip = GetIP();
            using (var tableInfo = DbHelper.GetTable<SmsLog>())
            {
                if (!CheckSms(tableInfo, (l) => l.Ip.Equals(ip), 60))
                {
                    return Json(new RequestResult
                    {
                        Message = "每个IP一分钟内最多发送一条"
                    });
                }
                else if (!CheckSms(tableInfo, (l) => l.DeviceId.Equals(deviceId), 120))
                {
                    return Json(new RequestResult
                    {
                        Message = "每个设备两分钟内最多发送一条"
                    });
                }
                else if (!CheckSms(tableInfo, (l) => l.Phone.Equals(phone), 120))
                {
                    return Json(new RequestResult
                    {
                        Message = "每个手机号码两分钟内最多发送一条"
                    });
                }
                else
                {
                    var result = Send(tableInfo, phone, deviceId, ip);
                    return Json(new RequestResult
                    {
                        Success = result.Success,
                        Message = result.Message,
                        Result = result.Key
                    });
                }

            }
        }

        public async Task<JsonResult> Register(string smsKey, string code)
        {
            using (var tableInfo = DbHelper.GetTable<SmsLog>())
            {
                if (!Guid.TryParseExact(smsKey, "D", out Guid smsGuid))
                {
                    return Json(new RequestResult
                    {
                        Message = "短信KEY错误"
                    });
                }
                if (!tableInfo.Table.Exists(smsGuid))
                {
                    return Json(new RequestResult
                    {
                        Message = "短信KEY不存在"
                    });
                }
                var log = tableInfo.Table[smsGuid];
                if (log.IsValidate)
                {
                    return Json(new RequestResult
                    {
                        Message = "短信KEY已经验证过"
                    });
                }
                if (log.CreateTime.AddMinutes(5) < DateTime.Now)
                {
                    return Json(new RequestResult
                    {
                        Message = "短信KEY已经过期"
                    });
                }
                var registerResult = await MemberSdkHelper.Get().RegisterAsync(log.Phone);
                if (!registerResult.Success)
                {
                    return Json(new RequestResult
                    {
                        Message = registerResult.Message
                    });
                }
                var memberInfoResult = await MemberSdkHelper.Get().GetMember<MemberInfo>(registerResult.MemberId);
                if (!memberInfoResult.Success)
                {
                    return Json(new RequestResult
                    {
                        Message = registerResult.Message
                    });
                }
                else
                {
                    return Json(new RequestResult
                    {
                        Success = true,
                        Result = memberInfoResult
                    });
                }
            }
        }
    }
}